#include "transmittance.h"
#include "ui_transmittance.h"

#include <QLineSeries>


Transmittance::Transmittance(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Transmittance)
{
    ui->setupUi(this);

    frameTypeEdit[SerialControl::UpTime] = ui->up_time;
    frameTypeEdit[SerialControl::DownTime] = ui->down_time;
    frameTypeEdit[SerialControl::MaxTransmit] = ui->max_transmit;
    frameTypeEdit[SerialControl::MinTransmit] = ui->min_transmit;
    frameTypeEdit[SerialControl::RuntimeTransmit] = ui->runtime_transmit;

    setTransmitCurve(QVector<double>(1000, 0));

    auto serialPortList = serialControl.getSerialPortList();
    for (auto& serialPort : serialPortList) {
        ui->serialport_list->addItem(serialPort.first + " : " + serialPort.second);
    }
    ui->serialport_list->setCurrentIndex(0);

    connect(ui->connect_serialport, &QPushButton::clicked, [&]() {
        QString portName = ui->serialport_list->currentText().split(":")[0].trimmed();
        bool ok = serialControl.open(portName);
        if (!ok) {
            ui->infomation->setText("open serial port error");
            return;
        }
        ui->infomation->setText("open serial port sucess");
    });

    connect(&serialControl, &SerialControl::received, this, &Transmittance::receive);
}

Transmittance::~Transmittance()
{
    delete ui;
}

void Transmittance::receive(SerialControl::FrameType frameType, QVector<double> frameValue)
{
    if (frameType == SerialControl::TransmitCurve) {
        setTransmitCurve(frameValue);
       return;
    }

    double value = frameValue[0];
    frameTypeEdit[frameType]->setText(QString::number(value));
}

void Transmittance::setTransmitCurve(const QVector<double> &curveValue)
{
    QChart* chart = new QChart;
    QLineSeries* lineSeries = new QLineSeries;

    for (int i = 0; i < curveValue.size(); ++i) {
        lineSeries->append(i, curveValue[i]);
    }

    chart->setTitle("透过率");
    chart->addSeries(lineSeries);
    chart->createDefaultAxes();

    ui->transmit_curve->setChart(chart);
}

